package com.yz.xyt.utils;

import com.yz.xyt.constant.Constants;
import com.yz.xyt.domain.Leave;
import com.yz.xyt.service.ILeaveService;
import com.yz.xyt.service.impl.LeaveServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import javax.servlet.ServletContextListener;
import java.text.DateFormat;
import java.util.Date;
import java.util.List;

/**
 * 定时任务调度
 */
@Component
public class SchedulingUtil {

    @Autowired
    private ILeaveService leaveService;

    /**
     * 超时未审批  2分组执行一次
     */
    @Async
    @Scheduled(fixedRate = 2*60*1000)
    @PostConstruct
    public void timeoutNotApproval(){
        System.out.println("超时未审批自动调度"+ DateFormat.getDateTimeInstance().format(new Date()));
        // 查询所有 未审批和审批中 且 无异常 的请假信息
        List<Leave> leaveList = leaveService.timeoutNotApproval();
        // 和当前时间进行比较，看谁否审批超时
        for (Leave leave:leaveList) {
            //  超时未审批
            if(leave.getEndTime().before(DateUtils.getNowDate())){
                System.out.println("超时未审批");
                leave.setRemark("超时未审批");
                leave.setStatus(Constants.LEAVE_TIME_OUT_NOT_APPROVAL);
                leave.setApprovalStatus(Constants.APPROVAL_STATUS_ERROR_STOP);
                leave.setUpdateBy("admin");
                leave.setUpdateDate(DateUtils.getNowDate());
                leaveService.updateByPrimaryKeySelective(leave);
            }
        }
    }

    /**
     * 超时未销假  2分组执行一次
     */
    @Async
    @Scheduled(fixedRate = 2*60*1000)
    @PostConstruct
    public void timeoutNotLeave(){
        System.out.println("超时未销假自动调度"+ DateFormat.getDateTimeInstance().format(new Date()));
        // 查询所有 请假中 且 无异常 的请假信息
        List<Leave> leaveList = leaveService.timeoutNotLeave();
        // 和当前时间进行比较，看谁否销假超时
        for (Leave leave:leaveList) {
            //  超时未审批
            if(leave.getEndTime().before(DateUtils.getNowDate())){
                System.out.println("超时未销假");
                leave.setStatus(Constants.LEAVE_TIME_OUT_NOT_CANCEL);
                leave.setRemark("超时未销假");
                leave.setUpdateBy("admin");
                leave.setUpdateDate(DateUtils.getNowDate());
                leaveService.updateByPrimaryKeySelective(leave);
            }
        }
    }
}
